#!/usr/bin/env bash
# script to automate extracting blobs from an existing vendor bios

board="${1}"
vendor_rom="${2}"

Print_help(){
	printf "Usage: ./build descriptors inte_blobs {boardname} {path/to/vendor_rom}\n"
	printf "Example: ./build descriptors intel_blobs x230 12mb_flash.bin\n"
	printf "\nYou need to specify exactly 2 arguments\n"
}

Build_deps(){
	if [ ! -d me_cleaner ]; then
		printf "downloading me_cleaner\n"
		./download me_cleaner
	else
		printf "me_cleaner already downloaded. Skipping.\n"
		printf "run ./download me_cleaner to manually overwrite\n"
	fi

	if [ ! -d coreboot ]; then
		printf "downloading coreboot\n"
		./download coreboot
	else
		printf "coreboot already downloaded. Skipping.\n"
		printf "run ./download coreboot to manually overwrite\n"
	fi

	printf "building ifdtool from coreboot\n"
	( cd coreboot/default/util/ifdtool && make )
}

Error_out(){
	printf "failed to extract ${1}\nmake sure that your rom dump is valid\n"
	exit 1
}


Extract_blobs(){
	# TODO: find a better way to know which coreboot config to source
	set -- "resources/coreboot/${board}/config/*"
	. ${1} 2>/dev/null
	. "resources/coreboot/${board}/board.cfg"

	if [ "$CONFIG_HAVE_MRC" = "y" ]; then
		printf 'haswell board detected, downloading mrc\n'
		./download mrc
	fi
	blob_destination="coreboot/${cbtree}/3rdparty/blobs/mainboard/${CONFIG_MAINBOARD_DIR}"

	_tmp_me=$(mktemp -t me_XXXXX.bin)
	_tmp_ifd=$(mktemp -t ifd_XXXXX.bin)

	# TODO: clean this up, it's kind of a hack way to make sure that the ime matches the ifd
	printf "extracting clean ime and modified ifd\n"
	mkdir -p ${blob_destination}
	./me_cleaner/me_cleaner.py -D ${_tmp_ifd} -M ${_tmp_ifd} ${vendor_rom} -t -r -S

	if [ ! -f ${blob_destination}/descriptor.bin ]; then
		mv ${_tmp_ifd} ${blob_destination}/descriptor.bin || Error_out ifd
	fi

	if [ ! -f ${blob_destination}/me.bin ]; then
		mv ${_tmp_me} ${blob_destination}/me.bin || Error_out me
	fi


	if [ ! -f ${blob_destination}/gbe.bin ]; then
	printf "extracting gigabit ethernet firmware"
	./coreboot/default/util/ifdtool/ifdtool -x ${vendor_rom}
	mv flashregion*gbe.bin ${blob_destination}/gbe.bin || Error_out gbe
	fi
	
	# Cleans up other files extracted with ifdtool
	rm flashregion*.bin 2> /dev/null
	printf "gbe, ifd, and me extracted to ${blob_destination}\n"
}

if [ ! -f "${vendor_rom}" ] ; then
	Print_help
	exit 1
fi

if [ ! -d "resources/coreboot/${board}" ]; then
	Print_help
        printf "build/roms: Target %s does not exist in the %s build system. Skipping build.\n" "${projectname}" "${board}"
        exit 1
fi

if [ ! -f "resources/coreboot/${board}/board.cfg" ]; then
	Print_help
        printf "build/roms: Target %s does not have a board.cfg. Skipping build.\n" "${board}"
        exit 1
fi

printf "extracting blobs for ${board} from ${vendor_rom}\n"
Build_deps
Extract_blobs
